﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using NotifyServices.Properties;

namespace NotifyServices
{
    public partial class frmServiceManager : Form
    {
        public AsynchronousServiceManager Manager;

        public ServiceController service;
        public string ServiceName = "MSSQLSERVER";
        
        /// <summary>
        /// Define a delegate for setting the status
        /// </summary>
        /// <param name="status">the status: START or STOP</param>
        /// <returns>true or false depending on the result of the status set</returns>
        public delegate bool SetServiceStateHelper(string status);

        /// <summary>
        /// create a member of type of previously created delegate
        /// </summary>
        public SetServiceStateHelper SetServiceState;

        public List<string> ServiceList = new List<string> { "MSSQLSERVER", "MSSQL$SQLEXPRESS", "MSSQL$SQL2008" };
        public frmServiceManager()
        {
            InitializeComponent();
            //ServiceName = "MSSQLSERVER";
            SetServiceState = new SetServiceStateHelper(SetService);
            Manager = new AsynchronousServiceManager();
            service = ServiceController.GetServices().ToList<ServiceController>().Find(p => p.ServiceName == ServiceName);
            label1.Text = ServiceName + " : " + service.Status.ToString();
            SetNotifyIcon();
            NotifyTooltip.SetToolTip(btnStart, "Quick Access to start/stop user services");
            Manager.Finished += new AsynchronousServiceManager.OnFinish(Manager_Finished);

            GetServiceStatus("MSSQL$SQLEXPRESS");

            ServiceControllerButton btn2008 = new ServiceControllerButton(".","MSSQL$SQLEXPRESS");
            Label lbl2008 = new Label() { Text = btn2008.Service.Service};
            btn2008.Dock = DockStyle.Left;
            btn2008.Click +=new EventHandler(btn2008_Update);
            btn2008.Finished += new ServiceControllerButton.OnFinish(delegate(ServiceResponse r){lbl2008.Text=r.CurrentStatus;});
            lbl2008.Dock = DockStyle.Fill;
            plService.Controls.Add(lbl2008); 
            plService.Controls.Add(btn2008);
            
        }

      
        public void btn2008_Update(object sender, EventArgs e)
        {
            (sender as ServiceControllerButton).UpdateService();
        }
        public void GetServiceStatus(string name)
        {
            ServiceController control = new ServiceController(name);
            if (control.Status == ServiceControllerStatus.Running)
            {
                btnStart2.Enabled = false;
                btnStop2.Enabled = true;
                label2.Text = name + " : RUNNING";
            }
            else if (control.Status == ServiceControllerStatus.Stopped)
            {
                btnStart2.Enabled = true;
                btnStop2.Enabled = false;
                label2.Text = name + " : STOPPED";
            }
            
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            SetServiceState.BeginInvoke("START", new AsyncCallback(CallbackMethod), null);
            imgLoader.Visible = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            SetServiceState.BeginInvoke("STOP", new AsyncCallback(CallbackMethod), null);
            imgLoader.Visible = true;
            label1.Text = ServiceName + " : " + "(waiting for update)";
        }

        private bool SetService(string state)
        {
            bool return_value = false;
            if (state == "START")
            {
                if (service.Status != ServiceControllerStatus.Running)
                {
                    service.Start(); 
                    service.WaitForStatus(ServiceControllerStatus.Running);
                    
                    return_value = true;
                }
            }
            else if (state == "STOP")
            {
                if (service.Status != ServiceControllerStatus.Stopped&&service.CanStop)
                {
                   
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                    return_value = true;
                }
            }
            return return_value;
        }
        private void CallbackMethod(IAsyncResult result)
        {
            bool endresult = SetServiceState.EndInvoke(result);
            if (endresult)
            {
                label1.Text = ServiceName + " : " + service.Status.ToString();
                imgLoader.Visible = false;
                SetNotifyIcon();
            }
            else
            {
                label1.Text = ServiceName + " failed to update";
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
           
            notifyIcon1.Visible = true;
            SetNotifyIcon();
            this.Visible = false;
        }

        private void SetNotifyIcon()
        {
            if (service.Status == ServiceControllerStatus.Running)
            {
                notifyIcon1.Icon = Properties.Resources.play;
                btnStart.Enabled = false;
                btnStop.Enabled = true;
            }
            else if (service.Status == ServiceControllerStatus.Stopped)
            {
                notifyIcon1.Icon = Properties.Resources.stop;
                btnStop.Enabled = false;
                btnStart.Enabled = true;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            notifyIcon1.Visible = false;
        }

        private void btnStart2_Click(object sender, EventArgs e)
        {
            Manager.Update("MSSQL$SQLEXPRESS", ".", "START");
            btnStop2.Enabled = true;
            btnStart2.Enabled = false;
        }

        

        private void btnStop2_Click(object sender, EventArgs e)
        {
            Manager.Update("MSSQL$SQLEXPRESS", ".", "STOP");
            btnStop2.Enabled = false;
            btnStart2.Enabled = true;
        }
        
        void Manager_Finished(ServiceResponse r)
        {
            label2.Text = string.Format("Service [{0}] on [{1}] is [{2}]", r.Service, r.Host, r.CurrentStatus);
        }

        private void btn2008_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SimpleTask task = new SimpleTask();
            task.Show();

        }
    }
}
